import express from "express";
import path from "path";
import { fileURLToPath } from "url";
import { generatePDF } from "./export.js";
import fs from "fs";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();

// 静态文件目录
app.use(express.static(path.join(__dirname, "public")));

// 首页（报告页面）
app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "public/index.html"));
});

// 导出 PDF 接口
// app.get("/export-pdf", async (req, res) => {
//   const reportPath = path.join(__dirname, "report.pdf");
//   const url = `http://localhost:8000/#/?reportId=62&token=Bearer%20eyJhbGciOiJIUzI1NiJ9.eyJsb2dpbl9pZCI6MSwiY3JlYXRlX3RpbWUiOjE3NjEwMTMyNDg1ODYsInVzZXJfbmFtZSI6Iuezu-e7n-euoeeQhuWRmCIsImFjY291bnQiOiJhZG1pbiIsImV4cCI6MTc2MTA1NjQ0OH0.YLIXGRzatSxhK8PWpBsKz2BdUkY-1UZOWhv3YEMdQEw&reportType=3`;

//   await generatePDF(url, reportPath);

//   res.download(reportPath, "report.pdf", (err) => {
//     if (!err) fs.unlinkSync(reportPath); // 下载后删除临时文件
//   });
// });

app.get("/export-pdf", async (req, res) => {
  const rawUrl = req.query.url;
  if (!rawUrl) {
    return res.status(400).send("缺少 url 参数，例如: /export-pdf?url=https%3A%2F%2Fexample.com");
  }

  const url = decodeURIComponent(String(rawUrl));
  if (!/^https?:\/\//i.test(url)) {
    return res.status(400).send("url 必须为以 http:// 或 https:// 开头的完整地址");
  }

  const reportPath = path.join(__dirname, `report-${Date.now()}.pdf`);

  try {
    await generatePDF(url, reportPath);
  } catch (err) {
    res.status(500).send("网页生成 PDF 失败，失败原因：" + err.toString());
  }

  try {
    res.download(reportPath, "report.pdf", (err) => {
      if (!err && fs.existsSync(reportPath)) fs.unlinkSync(reportPath); // 下载后删除临时文件
    });
  } catch (error) {
    if (fs.existsSync(reportPath)) fs.unlinkSync(reportPath);
    console.error("导出 PDF 失败：", err);
    res.status(500).send("导出 PDF 失败");
  }
});

app.listen(3001, () => {
  console.log("🚀 服务器已启动：http://localhost:3001");
  console.log("📄 导出 PDF 接口：http://localhost:3001/export-pdf");
});
